package com.ltt.service.impl;


import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.ltt.common.RedisKey;
import com.ltt.dao.pojo.User;
import com.ltt.dao.vo.Result;
import com.ltt.dao.vo.UserVo;
import com.ltt.dao.vo.Wx_Key;
import com.ltt.mapper.LoginMapper;
import com.ltt.service.WxLoginService;
import com.ltt.utils.JWTUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;


/**
 * @author ‘李天泰’
 * @version 1.0
 * @description: TODO
 * @date 2023/4/30 16:10
 */
@Service
public class WxLoginServiceImpl implements WxLoginService {

    @Value("${wx.appid}")
    private String appid;

    @Value("${wx.secret}")
    private String secret;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LoginMapper loginMapper;

    /**
     * @param code
     * @return com.ltt.dao.vo.Result
     * @description: 给用户返回sessionid
     */
    @Override
    public Result getUserInfo(String code) {
        /**
         *  1.首先通过code获得openid
         *  2.通过openid查找数据库，看是否存在此用户
         *  3.存在即直接返回此用户
         *  4.不存在，进行注册操作，然后在登录
         *  5.期间，通过openid生成token
         *  6.把token存储到redis中，值为用户的信息
         */

        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";
        url = url.replace("{0}", appid).replace("{1}", secret).replace("{2}", code);
        String res = HttpUtil.get(url);
        Wx_Key wx_key = new Wx_Key();
        wx_key = JsonToBean(res, wx_key);

        if(wx_key.getOpenid() == null){
            wx_key.setOpenid("");
        }

        User user = loginMapper.findUserById(wx_key.getOpenid());
        UserVo userVo = new UserVo();

        if (user != null) {
            BeanUtils.copyProperties(user, userVo);
            return login(userVo);
        } else {
            userVo.setOpenid(wx_key.getOpenid());
            return register(userVo);
        }
    }

    @Override
    public Result login(UserVo userVo) {
        String token = JWTUtils.sign(userVo.getId());
        userVo.setToken(token);
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("token", token);
        redisTemplate.opsForValue().set(RedisKey.TOKEN + token, JSON.toJSONString(userVo), 7, TimeUnit.DAYS);

        return Result.successWithData(userVo);
    }

    @Override
    public Result adminLogin(){
        User user = loginMapper.findUserById("admin");
        UserVo userVo = new UserVo();

        BeanUtils.copyProperties(user, userVo);
        return login(userVo);
    }

    @Override
    public Result register(UserVo userVo) {
        User user = new User();
        BeanUtils.copyProperties(userVo, user);
        loginMapper.insertUser(user);

        return login(userVo);
    }

    /**
     * @param json
     * @param bean
     * @return com.ltt.dao.vo.Wx_Key
     * @description: 将拿到的session_key和openid的字符串转为对象
     */
    public static Wx_Key JsonToBean(String json, Wx_Key bean) {
        bean = new Gson().fromJson(json, Wx_Key.class);
        return bean;
    }

}
